package product

import (
	"context"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/util/gconv"
	"hotgo/internal/model/entity"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"
	"hotgo/utility/simple"

	"hotgo/api/api/product/v1"
)

// IntegralBenefitsList 积分权益列表
func (c *ControllerV1) IntegralBenefitsList(ctx context.Context, req *v1.IntegralBenefitsListReq) (res *v1.IntegralBenefitsListRes, err error) {

	list, totalCount, err := service.Product().IntegralBenefitsList(ctx, &req.IntegralBenefitsInp)
	if err != nil {
		return nil, err
	}
	res = new(v1.IntegralBenefitsListRes)
	res.List = list
	res.PageRes.Pack(req, totalCount)
	return
}

// ProductGroupBuy 团购列表
func (c *ControllerV1) ProductGroupBuy(ctx context.Context, req *v1.ProductGroupBuyReq) (res *v1.ProductGroupBuyRes, err error) {

	list, totalCount, err := service.Product().ProductGroupBuyList(ctx, &req.ProductGroupBuyInp)
	if err != nil {
		return
	}
	res = new(v1.ProductGroupBuyRes)
	res.List = list
	res.PageRes.Pack(req, totalCount)

	return
}

// ProductInfo 商品详情
func (c *ControllerV1) ProductInfo(ctx context.Context, req *v1.ProductInfoReq) (res *v1.ProductInfoRes, err error) {
	model, err := service.Product().ProductInfo(ctx, &req.ProductInfoInp)
	if err != nil {
		return
	}
	res = new(v1.ProductInfoRes)
	res.ProductInfoModel = *model

	// 添加点击数
	simple.SafeGo(ctx, func(ctx context.Context) {
		err = service.Product().AddClick(ctx, model.Id)
		if err != nil {
			simple.Logf(glog.LEVEL_ERRO, ctx, "添加点击数失败：%v", err)
		}
	})
	return
}

// StoreInfo 门店详情
func (c *ControllerV1) StoreInfo(ctx context.Context, req *v1.StoreInfoReq) (res *v1.StoreInfoRes, err error) {
	res = new(v1.StoreInfoRes)
	res.Store = new(entity.Store)
	store, err := service.SysStore().View(ctx, &sysin.StoreViewInp{
		Id:  req.Id,
		Lat: req.Lat,
		Lng: req.Lng,
	})
	if err != nil {
		return
	}
	if store == nil {
		err = gerror.New("门店不存在")
		return
	}
	err = gconv.Scan(store, &res)
	if err != nil {
		return
	}
	return
}

// StoreGroupBuy 门店商品团购
func (c *ControllerV1) StoreGroupBuy(ctx context.Context, req *v1.StoreGroupBuyReq) (res *v1.StoreGroupBuyRes, err error) {
	list, totalCount, err := service.Product().StoreGroupBuy(ctx, &req.StoreGroupBuyInp)
	if err != nil {
		return nil, err
	}
	res = new(v1.StoreGroupBuyRes)
	res.List = list
	res.PageRes.Pack(req, totalCount)
	return
}

// SearchProduct 搜索商品
func (c *ControllerV1) SearchProduct(ctx context.Context, req *v1.SearchProductReq) (res *v1.SearchProductRes, err error) {
	list, totalCount, err := service.Product().SearchProduct(ctx, &req.SearchProductInp)
	if err != nil {
		return nil, err
	}
	res = new(v1.SearchProductRes)
	res.List = list
	res.PageRes.Pack(req, totalCount)
	return
}
